from rest_framework.generics import ListAPIView, RetrieveAPIView
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter

from .models import CourseCategory, Course
from .serializers import CourseCategorySerializer, CourseSerializer, CourseRetrieveSerializer
from .pagination import CoursePageNumberPagination


class CourseCategoryListAPIView(ListAPIView):
    queryset = CourseCategory.objects.filter(is_show=True, is_delete=False).order_by('orders')[:2]
    serializer_class = CourseCategorySerializer


class CourseListAPIView(ListAPIView):
    queryset = Course.objects.filter(is_show=True, is_delete=False).order_by('orders').all()
    serializer_class = CourseSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    # 查询的url http://www.xxxx.com/course/?course_category=xxxx
    # 设置支持设置的筛选过滤字段
    filter_fields = ['course_category', ]
    # 设置支持设置的排序字段   这些字段必须时Course模型中的字段
    # 查询的url http://www.xxxx.com/course/?ordering=id     倒叙 ?ordering=-id
    ordering_fields = ['id', 'students', 'price']
    pagination_class = CoursePageNumberPagination     # 设置分页器


class CourseRetrieveAPIView(RetrieveAPIView):
    queryset = Course.objects.filter(is_show=True, is_delete=False)
    serializer_class = CourseRetrieveSerializer


